package com.ruoyi.web.wuchuan.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.geom.MultiPolygon;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.AttributeTypeBuilder;
import org.geotools.feature.NameImpl;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.feature.type.AttributeTypeImpl;
import org.geotools.geojson.geom.GeometryJSON;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.util.SimpleInternationalString;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.geometry.aggregate.MultiPoint;
import org.opengis.geometry.coordinate.LineString;
import org.opengis.geometry.coordinate.Polygon;
import org.opengis.geometry.primitive.Point;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;

/**
 * @author by shixd
 * @date 2021/3/24
 * @desc
 */
public class JsonToShapUtils {


    public static String readFileContent(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr);
            }
            reader.close();
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return sbf.toString();
    }
        public static void geojson2Shape (String jsonPath, String shpPath){
            GeometryJSON gjson = new GeometryJSON();
            try {
                String strJson = jsonPath;
                JSONObject json = JSON.parseObject(strJson, Feature.IgnoreNotMatch);
                JSONArray features = json.getJSONArray("features");
                JSONObject feature0 = JSON.parseObject(features.getString(0), Feature.InitStringFieldAsEmpty);
                String strType = (feature0.getJSONObject("geometry")).getString("type");
                Map<String, Object> properties0 = (Map<String, Object>) feature0.getJSONObject("properties");

                Class<?> geoType = null;
                switch (strType) {
                    case "Point":
                        geoType = Point.class;
                        break;
                    case "MultiPoint":
                        geoType = MultiPoint.class;
                        break;
                    case "LineString":
                        geoType = LineString.class;
                        break;
                    case "MultiLineString":
                        geoType = MultiLineString.class;
                        break;
                    case "Polygon":
                        geoType = Polygon.class;
                        break;
                    case "MultiPolygon":
                        geoType = MultiPolygon.class;
                        break;
                }
                //创建shape文件对象
                File file = new File(shpPath);
                Map<String, Serializable> params = new HashMap<>();
                params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
                ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
                //设置编码
                Charset charset = Charset.forName("UTF-8");
                ds.setCharset(charset);

                //定义图形信息和属性信息
                SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
                tb.setCRS(DefaultGeographicCRS.WGS84);
                tb.setName("shapefile");
                tb.add("the_geom", geoType);
                tb.add("gid", Long.class);

                List<AttributeDescriptor> attributeDesList = new ArrayList<>();
                for (Entry<String, Object> entry : properties0.entrySet()) {
                    //属性构造器
                    AttributeTypeBuilder build = new AttributeTypeBuilder();
                    String name = entry.getKey();
                    build.setName(name);
                    build.setBinding(entry.getValue().getClass());
                    build.setDescription(name);
                    AttributeTypeImpl type = new AttributeTypeImpl(new NameImpl(name), entry.getValue().getClass(),
                            true, true, null, build.buildType(), new SimpleInternationalString(name));
                    String desString = type.getDescription().toString();
                    AttributeDescriptor descriptor = build.buildDescriptor(name, type);
                    attributeDesList.add(descriptor);
                }
                tb.addAll(attributeDesList);

                ds.createSchema(tb.buildFeatureType());


                try ( //设置Writer
                      FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT)) {
                    int index = 0;
                    System.out.println(index);
                    for (Iterator iterator = features.iterator(); iterator.hasNext(); ) {
                        JSONObject feature = (JSONObject) iterator.next();
                        Map<String, Object> properties = (Map<String, Object>) feature.getJSONObject("properties");
                        String strFeature = feature.toString();
                        System.out.println(strFeature);
                        Geometry geometry = gjson.read(strFeature);
                        System.out.println(geometry);
                        SimpleFeature simpleFeature = writer.next();
                        //System.out.println(feature);
                        simpleFeature.setAttribute("the_geom", geometry);
                        simpleFeature.setAttribute("gid", index);
                        for (Entry<String, Object> entry : properties.entrySet()) {
                            //simpleFeature.setAttribute(entry.getKey(), entry.getValue());
                            simpleFeature.setAttribute(entry.getKey(), entry.getValue());
                        }
                        writer.write();
                        index++;
                    }
                }
                ds.dispose();

            } catch (Exception e) {

                e.printStackTrace();
            }
        }


//        public static void main (String[]args) throws Exception {
//            //读取刚写完shape文件的图形信息
//            String filePath = "";
//            filePath = "D:\\shap\\test\\points.geojson";
//            String a = ShapToJsonFile.shp2json("D:\\shap\\2015年唐山市曹妃甸区九农场和柳赞镇高标准基本农田建设项目.shp");
//            geojson2Shape(a, "D:\\shap\\test\\test.shp");
//
//        }
    }
